package com.qidian.buy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.qidian.buy.util.jackson.LocalDateTimeDeserializer;
import com.qidian.buy.util.jackson.LocalDateTimeSerializer;

import javax.management.ObjectName;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @Description
 * @Time 2024/4/2 10:33
 */
public class Tools {

    public static String now(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public static boolean isBlank(String str){
        return str == null || "".equals(str.trim());
    }

    public static String object2json(Object obj){
        ObjectMapper mapper = new ObjectMapper();
        try {
            JavaTimeModule timeModule = new JavaTimeModule();
            timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
            mapper.registerModule(timeModule);
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将JSON字符串转换为对应的对象
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T json2object(String json,Class<T> clazz){
        ObjectMapper mapper = new ObjectMapper();
        try {
            JavaTimeModule timeModule = new JavaTimeModule();
            timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
            mapper.registerModule(timeModule);
            return mapper.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将字符串转为对应的即可
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> List<T> json2list(String json, Class<T> clazz){
        ObjectMapper mapper = new ObjectMapper();
        try {
            JavaTimeModule timeModule = new JavaTimeModule();
            timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
            mapper.registerModule(timeModule);
            return new ObjectMapper().readValue(json,new ObjectMapper().getTypeFactory().constructCollectionType(List.class,clazz));
            //return mapper.readValue(json, new TypeReference<List<T>>() {});
        }catch (JsonProcessingException e){
            throw new RuntimeException(e);
        }
    }
}
